package cn.itcast.hotel.listener;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 酒店监听者
 *
 * @author liudo
 * @version 1.0
 * @project hotel-demo
 * @date 2023/8/28 16:26:17
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class HotelListener {

    private final RestHighLevelClient restHighLevelClient;

    private final HotelMapper hotelMapper;

    /**
     * 酒店插入或更新监听器
     *
     * @param hotelId 酒店标识
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = "hotel.insert_update.queue"),
                    exchange = @Exchange(name = "hotel.direct"),
                    key = "hotel.insert_update"
            )
    )
    public void hotelInsertOrUpdateListener(Long hotelId) {
        log.info("-----------ES新增或更新:{}-----------", hotelId);
        // index
        try {
            IndexRequest indexRequest = new IndexRequest("hotel").id(String.valueOf(hotelId));
            // 获取最新的数据，我们从数据库查询 -- 实际上我们进行微服务的话 -- 单一原则 feign进行调用 调用酒店微服务
            Hotel hotel = hotelMapper.selectById(hotelId);
            // 实体转换
            HotelDoc hotelDoc = new HotelDoc(hotel);
            indexRequest.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("新增或更新失败", e);
        }
    }

    /**
     * 酒店删除监听器
     *
     * @param hotelId hotelId
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = "hotel.delete.queue"),
                    exchange = @Exchange(name = "hotel.direct"),
                    key = "hotel.delete"
            )
    )
    public void hotelDeleteListener(Long hotelId) {
        log.info("-----------ES删除:{}-----------", hotelId);
        // ES删除
        try {
            DeleteRequest request = new DeleteRequest("hotel", String.valueOf(hotelId));
            restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("ES数据删除失败", e);
        }
    }
}
